package com.luojun.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.coyote.Request;

import com.luojun.entity.Car;
import com.luojun.entity.Commodity;
import com.luojun.entity.User;
import com.luojun.service.CarService;
import com.luojun.service.UCommodityService;

/**
 * Servlet implementation class ToCarList
 */
@WebServlet("/ToCarList")
public class ToCarList extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ToCarList() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session  = request.getSession();
		User user= (User)session.getAttribute("user");	
		if(user==null){
			request.getRequestDispatcher("ToLogin").forward(request, response);
		}
		CarService cs = new CarService();
		List<Car> list = cs.find(user.getUserId());
		List<Commodity> commodityList =  new ArrayList<>();
		UCommodityService ucs = new UCommodityService();
		for (Car Car : list) {
			commodityList.add(ucs.findByCommodityId(Car.getCommodity().getCommodityId()));
		}
		int price = 0;
		for (Commodity commodity : commodityList) {
			price+=commodity.getPrice();
		}
		request.setAttribute("list", commodityList);
		request.setAttribute("price", price);
		request.getRequestDispatcher("WEB-INF/jsp/ShoppingCart.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
